package edu.uob;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TableReader {

    public static Table readTableFromFile(String filePath) {
        Table table = new Table();
        List<Row> rows = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            boolean isFirstLine = true;
            while ((line = br.readLine()) != null) {
                if (isFirstLine) {
                    // Extract column names from the first line
                    String[] columnNames = line.split("\t");
                    table.setColumnNames(Arrays.asList(columnNames));
                    System.out.println("Column names extracted: " + table.getColumnNames());

                    isFirstLine = false;
                } else {
                    // Extract data for each row
                    String[] rowData = line.split("\t");
                    System.out.println("Row data extracted: " + Arrays.toString(rowData));
                    System.out.println("Row data rowData.length: " + rowData.length);
                    System.out.println("table.getColumnNames().size(): " + table.getColumnNames().size());

                    if (rowData.length == table.getColumnNames().size()) {

                        Row row = new Row();
                        for (int i = 0; i < rowData.length; i++) {
                            row.addData(table.getColumnNames().get(i), rowData[i]);
                        }

                        rows.add(row);

                    } else {
                        System.out.println("Row data does not match the number of columns.");
                    }
                }
            }
            table.setRows(rows);
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
            return null;
        }

        // Set table name based on file name
        String[] parts = filePath.split("[\\\\/]");
        String fileName = parts[parts.length - 1];
        table.setTableName(fileName.substring(0, fileName.lastIndexOf(".")));
        return table;
    }
}
